using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using AgentFrameworkDemo.Models;
using AgentFrameworkDemo.Services;

namespace AgentFrameworkDemo;

/// <summary>
/// Microsoft官方标准风格的Agent工具演示
/// 基于https://learn.microsoft.com/zh-cn/azure/ai-services/agent-framework/agent-as-function-tool
/// </summary>
public class OfficialStyleDemo
{
    public static async Task RunAsync(string[] args)
    {
        Console.WriteLine("🚀 Microsoft官方标准Agent工具演示");
        Console.WriteLine("基于 Microsoft Agent Framework 官方文档");
        Console.WriteLine("=====================================\n");

        // 创建服务容器
        var services = new ServiceCollection();
        services.AddLogging(builder => builder.AddConsole());
        services.AddSingleton<IAgentManager, AgentManager>();
        services.AddSingleton<IMemoryManager, MemoryManager>();
        services.AddSingleton<IToolManager, ToolManager>();
        services.AddSingleton<ISystemPromptService, SystemPromptService>();
        services.AddHttpClient();

        var serviceProvider = services.BuildServiceProvider();

        try
        {
            var agentManager = serviceProvider.GetRequiredService<IAgentManager>();
            var logger = serviceProvider.GetRequiredService<ILogger<OfficialStyleDemo>>();

            Console.WriteLine("📝 创建诗词专家Agent（模拟官方AIAgent模式）...");

            // 创建诗词专家Agent（模拟官方示例中的weatherAgent）
            var poetryAgentDefinition = new AgentDefinition
            {
                Name = "PoetryExpert",
                Description = "An agent that analyzes Chinese classical poetry",
                Tags = ["tool", "poetry", "literature", "expert"],
                Capabilities = new AgentCapabilities
                {
                    EnableMemory = true,
                    EnableTools = false
                },
                Configuration = new AgentConfiguration
                {
                    Model = new AIModelConfig
                    {
                        Provider = "ZhipuAI",
                        ModelId = "glm-4.5",
                        ApiKey = "08ffd1f87b0e4914be6542b892d327cd.QKnNO0dKRUljxxXv",
                        Endpoint = "https://open.bigmodel.cn/api/paas/v4/chat/completions",
                        Temperature = 0.8,
                        MaxTokens = 300
                    }
                },
                Metadata = new Dictionary<string, object>
                {
                    ["instructions"] = "You are an expert in Chinese classical poetry. Analyze poems with deep cultural and literary insights.",
                    ["category"] = "literary_analysis",
                    ["language"] = "chinese"
                }
            };

            var poetryAgent = await agentManager.CreateAgentAsync(poetryAgentDefinition);
            Console.WriteLine($"✅ 诗词专家创建成功: {poetryAgent.Id}");

            Console.WriteLine("\n🔄 Microsoft官方风格转换: poetryAgent.AsAIFunction()");

            // 使用我们的AgentFunctionTool模拟官方的.AsAIFunction()方法
            AgentFunctionTool.Initialize(serviceProvider);
            var poetryFunction = poetryAgent.AsAIFunction("poetry_expert", "Chinese classical poetry analysis expert");
            Console.WriteLine($"✅ 转换成功: {poetryFunction.Name}");

            // 创建主Agent（模拟官方示例中的主代理）
            var mainAgentDefinition = new AgentDefinition
            {
                Name = "MainAssistant",
                Description = "A helpful assistant that can coordinate with poetry experts",
                Tags = ["assistant", "coordinator"],
                Capabilities = new AgentCapabilities
                {
                    EnableMemory = true,
                    EnableTools = true  // 主代理需要启用工具功能
                },
                Configuration = new AgentConfiguration
                {
                    Model = new AIModelConfig
                    {
                        Provider = "ZhipuAI",
                        ModelId = "glm-4.5",
                        ApiKey = "08ffd1f87b0e4914be6542b892d327cd.QKnNO0dKRUljxxXv",
                        Endpoint = "https://open.bigmodel.cn/api/paas/v4/chat/completions",
                        Temperature = 0.7,
                        MaxTokens = 400
                    }
                },
                Metadata = new Dictionary<string, object>
                {
                    ["instructions"] = "You are a helpful assistant who can coordinate with poetry experts when needed. Always provide thoughtful responses.",
                    ["available_tools"] = new[] { "poetry_expert" }
                }
            };

            var mainAgent = await agentManager.CreateAgentAsync(mainAgentDefinition);
            Console.WriteLine($"✅ 主助手创建成功: {mainAgent.Id}");

            Console.WriteLine("\n📖 模拟官方示例：主代理调用诗词专家工具");
            Console.WriteLine("用户问题：请分析'问君能有几多愁'的诗意");

            // 直接使用poetryFunction模拟官方调用方式
            var result = await poetryFunction.InvokeWithStringInputAsync(
                "请分析李煜的词句'问君能有几多愁，恰似一江春水向东流'的意境和情感表达");

            // 展示结果（模拟官方输出格式）
            Console.WriteLine("\n🎨 诗词分析结果:");
            if (result is Dictionary<string, object> dict)
            {
                var content = dict.GetValueOrDefault("content")?.ToString() ?? "无内容";
                var success = dict.GetValueOrDefault("success")?.ToString();

                Console.WriteLine($"✅ 执行状态: {success}");
                Console.WriteLine($"📖 分析内容:");
                Console.WriteLine("----------------------------------------");
                Console.WriteLine(content);
                Console.WriteLine("----------------------------------------");

                // 显示Microsoft风格的元数据
                if (dict.TryGetValue("enterprise", out var enterpriseInfo) &&
                    enterpriseInfo is Dictionary<string, object> enterprise)
                {
                    Console.WriteLine($"\n🏢 企业级特性 (Microsoft风格增强):");
                    Console.WriteLine($"📊 审计ID: {enterprise.GetValueOrDefault("audit_log_id")}");

                    if (enterprise.TryGetValue("performance_metrics", out var perf) &&
                        perf is Dictionary<string, object> metrics)
                    {
                        Console.WriteLine($"⚡ 执行时间: {metrics.GetValueOrDefault("total_execution_time_ms")}ms");
                    }
                }
            }

            Console.WriteLine("\n📊 对比官方标准:");
            Console.WriteLine("✅ 官方风格: agent.AsAIFunction() - 一行代码转换");
            Console.WriteLine("✅ 我们的实现: agent.AsAIFunction() - 同样简洁");
            Console.WriteLine("✅ 企业级增强: 审计日志、性能监控、错误处理");
            Console.WriteLine("✅ 兼容性: 与官方API概念完全兼容");

            Console.WriteLine("\n🎉 Microsoft官方标准演示完成！");
            Console.WriteLine("我们的实现既保持了官方API的简洁性，又增加了企业级功能");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"\n❌ 演示失败: {ex.Message}");
            Console.WriteLine("请检查API密钥和网络连接");
        }

        Console.WriteLine("\n按Enter键退出...");
        try
        {
            Console.ReadLine();
        }
        catch (InvalidOperationException)
        {
            // 在没有控制台的情况下忽略异常
        }
    }
}